import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:drift/drift.dart' as drift;
import '../../../core/network/stock_api_service.dart';
import '../../../data/models/buy_record_model.dart';
import '../../../data/models/sell_record_model.dart';
import '../../../data/models/stock_position_model.dart';
import '../../../data/datasource/local/database.dart';


class PositionController extends GetxController {
  final AppDatabase _database = Get.find();
  final StockApiService _apiService = Get.find();

  var isLoading = false.obs;
  var observablePositions = <ObservableStockPosition>[].obs;
  var filteredPositions = <ObservableStockPosition>[].obs;
  var errorMessage = ''.obs;
  var searchQuery = ''.obs;
  var showClearedStocks = false.obs;
  var filterPercent = 3.0.obs; // Changed default to 3.0

  @override
  void onInit() {
    super.onInit();
    fetchStockPositions();
  }

  // 获取所有股票持仓
  Future<void> fetchStockPositions() async {
    try {
      isLoading(true);
      errorMessage('');

      // 从数据库获取所有买入记录
      final buyRecords = await _database.allBuyRecords;

      // 从数据库获取所有卖出记录
      final sellRecords = await _database.allSellRecords;

      // 按股票代码分组
      final Map<String, List<BuyRecordModel>> buyRecordsBySymbol = {};
      final Map<String, List<SellRecordModel>> sellRecordsBySymbol = {};
      final Map<String, String> stockNames = {};

      for (final record in buyRecords) {
        final model = BuyRecordModel(
          id: record.id,
          symbol: record.symbol,
          name: record.name,
          buyPrice: record.buyPrice,
          quantity: record.quantity,
          remainingQuantity: record.remainingQuantity,
          buyDate: record.buyDate,
          createdAt: record.createdAt,
        );

        if (!buyRecordsBySymbol.containsKey(record.symbol)) {
          buyRecordsBySymbol[record.symbol] = [];
        }
        buyRecordsBySymbol[record.symbol]!.add(model);
        stockNames[record.symbol] = record.name;
      }

      for (final record in sellRecords) {
        final model = SellRecordModel(
          id: record.id,
          buyRecordId: record.buyRecordId,
          sellPrice: record.sellPrice,
          sellQuantity: record.sellQuantity,
          sellDate: record.sellDate,
        );

        // 找到对应的买入记录以获取股票代码
        final buyRecord = buyRecords.firstWhere((b) => b.id == record.buyRecordId);
        final symbol = buyRecord.symbol;

        if (!sellRecordsBySymbol.containsKey(symbol)) {
          sellRecordsBySymbol[symbol] = [];
        }
        sellRecordsBySymbol[symbol]!.add(model);
      }

      // 创建股票持仓模型
      final List<ObservableStockPosition> positions = [];

      for (final symbol in buyRecordsBySymbol.keys) {
        final position = StockPositionModel(
          symbol: symbol,
          name: stockNames[symbol] ?? symbol,
          buyRecords: buyRecordsBySymbol[symbol]!,
          sellRecords: sellRecordsBySymbol[symbol] ?? [],
        );

        positions.add(ObservableStockPosition(position: position));
      }

      observablePositions.assignAll(positions);

      // 获取最新股价
      await _fetchCurrentPrices();

      _filterPositions();
    } catch (e) {
      errorMessage('获取持仓数据失败: $e');
    } finally {
      isLoading(false);
    }
  }

  // 获取最新股价
  Future<void> _fetchCurrentPrices() async {
    for (final observablePosition in observablePositions) {
      try {
        final data = await _apiService.fetchStockData(observablePosition.position.symbol);
        final parts = data.split(',');

        if (parts.length > 3) {
          final currentPrice = double.parse(parts[3]);
          final yesterdayClose = double.parse(parts[2]);
          final changePercent = ((currentPrice - yesterdayClose) / yesterdayClose) * 100;

          // 只更新价格和涨跌幅，不重建整个对象
          observablePosition.currentPrice.value = currentPrice;
          observablePosition.changePercent.value = changePercent;
        }
      } catch (e) {
        // 忽略单个股票获取失败的情况
        print('获取 ${observablePosition.position.symbol} 股价失败: $e');
      }
    }

    _filterPositions();
  }

  // 删除买入记录
  Future<void> deleteBuyRecord(int id) async {
    try {
      final database = Get.find<AppDatabase>();

      // 先删除相关的卖出记录
      final sellRecords = await database.getSellRecordsByBuyId(id);
      for (final record in sellRecords) {
        await database.deleteSellRecord(record.id);
      }

      // 删除买入记录
      await database.deleteBuyRecord(id);
      await fetchStockPositions();

      Get.snackbar(
        '成功',
        '已删除买入记录及相关卖出记录',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[900],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '删除买入记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
    }
  }

  // 删除卖出记录
  Future<void> deleteSellRecord(int id, int buyRecordId) async {
    try {
      final database = Get.find<AppDatabase>();

      // 获取卖出记录
      final sellRecords = await database.getSellRecordsByBuyId(buyRecordId);
      final sellRecord = sellRecords.firstWhere((record) => record.id == id);

      if (sellRecord == null) {
        throw Exception('卖出记录不存在');
      }

      // 获取买入记录
      final buyRecord = await database.getBuyRecordById(buyRecordId);
      if (buyRecord == null) {
        throw Exception('买入记录不存在');
      }

      // 删除卖出记录
      await database.deleteSellRecord(id);

      // 恢复买入记录的剩余数量
      final newRemainingQuantity = buyRecord.remainingQuantity + sellRecord.sellQuantity;
      await database.updateRemainingQuantity(buyRecordId, newRemainingQuantity);

      await fetchStockPositions();

      Get.snackbar(
        '成功',
        '已删除卖出记录',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[900],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      Get.snackbar(
        '错误',
        '删除卖出记录失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[900],
        duration: const Duration(seconds: 4),
      );
    }
  }

  // 设置显示已清仓股票
  void setShowClearedStocks(bool value) {
    showClearedStocks.value = value;
    _filterPositions();
  }

  // 设置过滤百分比
  void setFilterPercent(double value) {
    filterPercent.value = value;
    _filterPositions();
  }

  // 根据搜索查询过滤持仓
  void setSearchQuery(String query) {
    searchQuery.value = query;
    _filterPositions();
  }

  // 计算盈亏比率
  double _calculateProfitLossRate(ObservableStockPosition observablePosition) {
    final position = observablePosition.position;
    final currentPrice = observablePosition.currentPrice.value;

    if (position.averageCost > 0) {
      return ((currentPrice - position.averageCost) / position.averageCost) * 100;
    }
    return 0.0;
  }

  // 过滤持仓
  void _filterPositions() {
    if (searchQuery.isEmpty) {
      // 应用盈亏比率过滤和清仓股票过滤
      filteredPositions.assignAll(observablePositions.where((observablePosition) {
        final profitLossRate = _calculateProfitLossRate(observablePosition);
        final meetsPercentFilter = filterPercent.value == 0.0 ||
            (profitLossRate >= filterPercent.value && filterPercent.value > 0) ||
            (profitLossRate <= filterPercent.value && filterPercent.value < 0);

        final meetsClearedFilter = showClearedStocks.value || observablePosition.position.totalQuantity > 0;

        return meetsPercentFilter && meetsClearedFilter;
      }).toList());
    } else {
      final query = searchQuery.value.toLowerCase();
      filteredPositions.assignAll(observablePositions.where((observablePosition) {
        final position = observablePosition.position;
        final matchesSearch = position.symbol.toLowerCase().contains(query) ||
            position.name.toLowerCase().contains(query);

        final profitLossRate = _calculateProfitLossRate(observablePosition);
        final meetsPercentFilter = filterPercent.value == 0.0 ||
            (profitLossRate >= filterPercent.value && filterPercent.value > 0) ||
            (profitLossRate <= filterPercent.value && filterPercent.value < 0);

        final meetsClearedFilter = showClearedStocks.value || position.totalQuantity > 0;

        return matchesSearch && meetsPercentFilter && meetsClearedFilter;
      }).toList());
    }
  }

  // 获取股票的交易历史
  Future<List<Map<String, dynamic>>> getTradeHistory(String symbol) async {
    try {
      // 获取买入记录
      final buyRecords = await _database.getBuyRecordsBySymbol(symbol);
      final buyRecordsList = buyRecords.map((record) => BuyRecordModel(
        id: record.id,
        symbol: record.symbol,
        name: record.name,
        buyPrice: record.buyPrice,
        quantity: record.quantity,
        remainingQuantity: record.remainingQuantity,
        buyDate: record.buyDate,
        createdAt: record.createdAt,
      )).toList();

      // 获取卖出记录
      final sellRecordsList = <SellRecordModel>[];
      for (final buyRecord in buyRecordsList) {
        final sells = await _database.getSellRecordsByBuyId(buyRecord.id);
        for (final sell in sells) {
          sellRecordsList.add(SellRecordModel(
            id: sell.id,
            buyRecordId: sell.buyRecordId,
            sellPrice: sell.sellPrice,
            sellQuantity: sell.sellQuantity,
            sellDate: sell.sellDate,
          ));
        }
      }

      // 合并记录并按时间排序
      final List<Map<String, dynamic>> history = [];

      for (final buyRecord in buyRecordsList) {
        history.add({
          'type': 'buy',
          'id': buyRecord.id,
          'price': buyRecord.buyPrice,
          'quantity': buyRecord.quantity,
          'remaining': buyRecord.remainingQuantity,
          'date': buyRecord.buyDate,
          'createdAt': buyRecord.createdAt,
        });
      }

      for (final sellRecord in sellRecordsList) {
        history.add({
          'type': 'sell',
          'id': sellRecord.id,
          'buyRecordId': sellRecord.buyRecordId,
          'price': sellRecord.sellPrice,
          'quantity': sellRecord.sellQuantity,
          'date': sellRecord.sellDate,
        });
      }

      // 按日期排序
      history.sort((a, b) => b['date'].compareTo(a['date']));

      return history;
    } catch (e) {
      errorMessage('获取交易历史失败: $e');
      return [];
    }
  }

  // 卖出股票
  Future<bool> sellStock({
    required int buyRecordId,
    required double sellPrice,
    required int sellQuantity,
    required DateTime sellDate,
  }) async {
    try {
      // 获取原始记录
      final originalRecord = await _database.getBuyRecordById(buyRecordId);
      if (originalRecord == null) {
        throw Exception('记录不存在');
      }

      // 检查卖出数量是否有效
      if (sellQuantity > originalRecord.remainingQuantity) {
        throw Exception('卖出数量不能超过剩余数量');
      }

      // 插入卖出记录
      final sellCompanion = SellRecordsCompanion(
        buyRecordId: drift.Value(buyRecordId),
        sellPrice: drift.Value(sellPrice),
        sellQuantity: drift.Value(sellQuantity),
        sellDate: drift.Value(sellDate),
      );

      await _database.insertSellRecord(sellCompanion);

      // 更新买入记录的剩余数量
      final newRemainingQuantity = originalRecord.remainingQuantity - sellQuantity;
      await _database.updateRemainingQuantity(buyRecordId, newRemainingQuantity);

     // await fetchStockPositions();

      return true;
    } catch (e) {
      errorMessage('卖出操作失败: $e');
      return false;
    }
  }

// 刷新指定股票的数据
  Future<void> refreshVisibleStocks(List<String> symbols) async {
    try {
      for (final symbol in symbols) {
        // 找到对应的observablePosition
        final observablePosition = observablePositions.firstWhere(
              (obs) => obs.position.symbol == symbol,
          orElse: () => ObservableStockPosition(  // 返回一个默认的实例而不是 null
            position: StockPositionModel(
              symbol: symbol,
              name: symbol,
              buyRecords: [],
              sellRecords: [],
            ),
          ),
        );

        // 检查是否找到了有效的持仓
        if (observablePosition.position.buyRecords.isEmpty) {
          continue; // 跳过不存在的持仓
        }

        try {
          final data = await _apiService.fetchStockData(symbol);
          final parts = data.split(',');

          if (parts.length > 3) {
            final currentPrice = double.parse(parts[3]);
            final yesterdayClose = double.parse(parts[2]);
            final changePercent = ((currentPrice - yesterdayClose) / yesterdayClose) * 100;

            observablePosition.currentPrice.value = currentPrice;
            observablePosition.changePercent.value = changePercent;
          }
        } catch (e) {
          print('刷新股票 $symbol 数据失败: $e');
        }
      }
      // 刷新过滤后的持仓列表
      _filterPositions();
    } catch (e) {
      print('刷新可见股票数据失败: $e');
    }
  }

  // 添加下拉刷新方法
  Future<void> refreshData() async {
    await fetchStockPositions();
  }
}

class ObservableStockPosition {
  final StockPositionModel position;
  final RxBool isExpanded;
  final RxDouble currentPrice;
  final RxDouble changePercent;

  ObservableStockPosition({
    required this.position,
    bool isExpanded = false,
    double currentPrice = 0.0,
    double changePercent = 0.0,
  })  : isExpanded = isExpanded.obs,
        currentPrice = currentPrice.obs,
        changePercent = changePercent.obs;
}